// 用户vuex 数据模块

import {checkLoginReq, getUserInfoReq} from '@/api/user'

const state = {
  token: localStorage.getItem('t_k'),
  role: localStorage.getItem('role'),
  userInfo: {},
}

const getters = {}
const mutations = {
  SET_TOKEN(state, data) {
    state.token = data
    // 储存到本地
    localStorage.setItem('t_k', data)
  },
  SET_ROLE(state, data) {
    state.role = data
    localStorage.setItem('role', data)
  },
  SET_USERINFO(state, data) {
    state.userInfo = data
  },
  CLEAR(state) {
    ;(state.userInfo = {}),
      (state.role = ''),
      (state.token = ''),
      // 清空本地
      localStorage.clear()
  },
}
const actions = {
  // 登录
  async A_login({commit}, data) {
    return new Promise(async (resolve, reject) => {
      // 发送请求
      let res = await checkLoginReq(data)
      // 解构数据
      let {code, msg, token, role} = res.data
      // 判断
      if (code === 0) {
        commit('SET_TOKEN', 'Bearer ' + token)
        commit('SET_ROLE', role)
        //   调用
        resolve()
      }
    })
  },
  // 获取用户信息
  A_getUserInfo({commit}) {
    return new Promise(async (resolve, reject) => {
      // let res = await getUserInfoReq()
      // commit('SET_USER_INFO', res.data)
      // resolve()

      getUserInfoReq()
        .then(res => {
          commit('SET_USERINFO', res.data)
          resolve()
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  // 退出登录清空数据
  A_clear({commit}) {
    return new Promise(resolve => {
      commit('CLEAR')

      resolve()
    })
  },
}
export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
}
